package org.u2ml.app.rest;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import org.u2ml.app.business.ConnectedUserService;
import org.u2ml.app.business.UserService;
import org.u2ml.app.domain.ConnectedUser;
import org.u2ml.app.domain.Connection;
import org.u2ml.app.domain.RESTResponse;
import org.u2ml.app.domain.User;

@Component
@Path("/connect")
public class ConnectionResource {

	@Autowired private ConnectedUserService connectedUserService;
	@Autowired private UserService userService;

	@POST
	@Produces(MediaType.TEXT_XML)
	public RESTResponse newConnection(Connection connection) {
		RESTResponse response = new RESTResponse();
		if ((connection.getEmail() == null) || (connection.getEmail().isEmpty()) ||
			(connection.getPassword() == null) || (connection.getPassword().isEmpty()))
			throw new WebApplicationException(Status.BAD_REQUEST);
		User u = userService.findByEmail(connection.getEmail());
		if (u == null || !u.getPassword().equals(connection.getPassword()))
			response.setErrorCode("login_incorrect_information");
		else {
			ConnectedUser c = connectedUserService.add(u);
			response.addData(c);
		}
		return response;
	}
	
	@GET
	@Produces(MediaType.TEXT_XML)
	public RESTResponse testConnection(@QueryParam("SESSIONID") Long sessionId) {
		RESTResponse response = new RESTResponse();
		if (sessionId==null)
			response.addData(null);
		else {
			ConnectedUser c = connectedUserService.find(sessionId);
			if (c==null)
				response.addData(null);
			else {
				response.addData(c.getUser());
			}
		}
		return response;
	}

	@GET
	@Path("/disconnect")
	@Produces(MediaType.TEXT_XML)
	public RESTResponse disconnect(@QueryParam("SESSIONID") Long oid) {
		RESTResponse response = new RESTResponse();
		connectedUserService.delete(oid);
		response.addData(null);
		return response;
	}

}
